package ns3

import (
	"context"
	"fmt"
	"github.com/hpcloud/tail"
	"io"
)

func LastNRows(filename string, n int64) (rows []string, err error) {
	t, err := tail.TailFile(filename, tail.Config{Location: &tail.SeekInfo{-n * 34, io.SeekEnd}})
	for line := range t.Lines {
		fmt.Println(line.Text)
	}
	err = t.Stop()

	return
}

func Follow(context context.Context, filename string, source Source, rows chan SourcedLine) error {
	t, err := tail.TailFile(filename, tail.Config{Follow: true, Location: &tail.SeekInfo{0, io.SeekStart}})
	if err != nil {
		return err
	}
	for {
		select {
		case <-context.Done():
			//log.Println("closing the loop of ", filename)
			break
		case line := <-t.Lines:
			if line != nil {
				rows <- SourcedLine{
					Source: source,
					Raw:    line.Text,
				}
			}

		}
	}

	return nil
}
